#!/usr/bin/python

############################################
#
#  Uploader for Picasa
#
#
#  http://code.google.com/p/cens-image-feature-viz/
#
############################################
"""This uploader allows automated uploading of files 
to Picasa Web Albums.  It requires a valid Google account.
	
	Sample:
	#Upload all pictures in /your/directory to CoolAlbum
	# using account AcctName
	#If CoolAlbum does not exist, it will be created.
	#If it does exist, append all pictures to this album.
	
	upload -d /your/directory -u AcctName -a CoolAlbum  
    
	#Upload the picture /directory/photo to OtherAlbum

	upload -p /directory/photo -u AcctName -a OtherAlbum

	#Upload the picture /other/directory/photo 
	#  This will create an album "/other/directory".

	upload -p /other/directory/photo -u AcctName
    
"""
__author__ = u'thisismike04@gmail.com' #'Mike Wilson'
__license__ = 'Apache License v2'
__version__ = 'Revision 16'


import gdata.photos, gdata.photos.service
import sys, os, getopt, getpass
from tools import client


def gather_arguments(argv):
###################################
#  Builds a dict out of the arguments
###################################
	
	state = {}

	if (len(argv) < 1):
		usage()
		sys.exit(2)
	
	try:
		opts, args = getopt.getopt(argv, "hd:p:a:u:s:", ["help", "user", "debug"])
	except getopt.GetoptError:          
			usage()                         
			sys.exit(2)                     
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			usage()                     
			sys.exit(1)                  
		elif opt == '-d':
			if not os.path.isdir(arg):
				print('%s is not a directory') % arg
				sys.exit(1)
			state["_dir"] = arg                   
		elif opt == '-p':
			if not os.path.isfile(arg):
				print ('%s is not a file') % arg
				sys.exit(1)
			state["_photo"] = arg
		elif opt == '-a':
			state["_album"] = arg
		elif opt == '-s':
			state["_pass"] = arg
		elif opt in ("-u", "--user"):
			state["_user"] = arg
		elif opt == "--debug":
			state['_debug'] = 1;
		else:
			usage()
			sys.exit(1)
	
	if not state.has_key("_user"):
		state["_user"] = raw_input('Username: ')
	if not state.has_key("_photo") and not state.has_key("_dir"):
		print("Please provide filename or directory to upload.")
		sys.exit(1)
	


	return state

##################################################################
#    Upload class:

##################################################################

class Uploader:
	
	def __init__(self, client, arguments):
		#  First, check the arguments to fail early
		
		self.client = client
		self.args = arguments
		self.image_list = []
		self.album = None	

	def upload(self):	
		if self.args.has_key("_dir"):
			for root, dirs, files in os.walk(self.args['_dir']):
				for name in files:
					self.image_list.append(os.path.abspath(os.path.join(root, name)))
		
		if self.args.has_key('_photo'):
			self.image_list.append((self.args['_photo']))
				
		if not self.args.has_key('_album'):
			self.args['_album'] = os.path.dirname(self.image_list[0]).split('/')[-1]

		self.getAlbum()
		self.pushImages()


	def getAlbum(self):
		albumuri = 'http://picasaweb.google.com/data/feed/api/user/'+ self.args['_user'] +'?kind=album'

		UserFeed = self.client.GetFeed(albumuri)

		for album in UserFeed.entry:
			if album.title.text == self.args['_album']:
				self.album = album
				return
		self.album = self.client.InsertAlbum(self.args['_album'])

	def pushImages(self):
		for filename in self.image_list:
			imagename = os.path.basename(filename)
			print ("Loading image %s to album %s" % (imagename, self.args['_album']) )

	       	 	try:
	                	# Insert new photo
        			tag = "path=" + os.path.abspath(filename)
       	       			newphoto = self.client.InsertPhotoSimple(self.album, imagename, imagename, filename, tag)
          			print('Image %s loaded successfully.' % imagename)
				if (self.args.has_key('_debug')):
					print('imagename = %s filename = %s tag = %s') % (imagename, filename, tag)
	        	except gdata.photos.service.GooglePhotosException:
         	 		print ('File %s is not an image. Item not loaded.' % imagename)

	
##########################################
def usage():
##########################################
# Print usage
##########################################
        print """
        usage: upload  [-d DIRECTORY] [-p PHOTONAME]
                [-a ALBUMNAME] [-u|--user USERNAME]

        Required: (-p and/or -a)
        Notes:
                If no albumname is given, will create or append
			album with name of directory or image.
                Directory defaults to '.'
                """

if __name__ == "__main__":
	if (len(sys.argv) < 2):
		usage()
		sys.exit(2)
	args = 	gather_arguments(sys.argv[1:])
	client = client.Client(args['_user'] + '@gmail.com')
	if (args.has_key('_pass')):
		client.autologin(args['_pass'])
	else:
		client.login()
	uploader = Uploader(client, args)
	uploader.upload()
		

